/*
 *  Copyright 2011 Iurii Dunko, Iana Potochniak.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.yyminijava.syntaxtree;

import java.util.ArrayList;
import java.util.List;

import org.opu.yyminijava.syntaxtree.primary.Primary;
import org.opu.yyminijava.syntaxtree.primary.PrimaryFromLiteral;
import org.opu.yyminijava.visitor.Visitor;

/**
 * 
 * @author Iurii Dunko
 * @author Iana Potochniak
 */
public class PostfixExpression implements Rule {

	private static final long serialVersionUID = 1323110697211L;

	private Primary primary;
	private List<Suffix> suffixs = new ArrayList<Suffix>();

	public PostfixExpression(Primary primary, List<Suffix> suffixs) {
		this.primary = primary;
		this.suffixs = suffixs;
	}
	
	public PostfixExpression(Primary primary) {
		this.primary = primary;
	}

	public PostfixExpression() {
	}

	public Primary getPrimary() {
		return primary;
	}

	public void setPrimary(Primary primary) {
		this.primary = primary;
	}

	public List<Suffix> getSuffixs() {
		return suffixs;
	}

	public void setSuffixs(List<Suffix> suffixs) {
		this.suffixs = suffixs;
	}

	public boolean addSuffix(Suffix e) {
		return suffixs.add(e);
	}

    public void validate(){
        if (primary instanceof PrimaryFromLiteral){
            Class c = ((PrimaryFromLiteral) primary).getLiteral().getClass();
            if (c != StringLiteral.class) {
                if (!suffixs.isEmpty()) {
                    // TODO: create own exception struction!
                    // Using error is temporary solution, we use exception when the
                    // incoming file contains errors, when the problem in our compiler
                    // we use errors (but it for now)
                    throw new Error("Illegal expression " + toString());
                }
            }
        } 
    }

	@Override
	public String toString() {
		return String.valueOf(primary) + (suffixs.isEmpty() ? "" : suffixs.toString());
	}

    @Override
    public void accept(Visitor visitor) {
        visitor.visit(primary);
        for (Suffix suffix : suffixs) {
            visitor.visit(suffix);
        }
    }
}